/**
 * 主要处理key的后缀
 */
function generateChildrenByFunc(child, index, func = c => [c]) {
  const prefixKey = child.key;
  let children = func(child, index);
  if (Array.isArray(children)) {
    return children.map((_child, i) => {
      _child.key = _child.key ? `${prefixKey}/.$${_child.key}` : `${prefixKey}/.${i}`
      return _child;
    });
  } else {
    children.key = children.key ? `${children.key}/${prefixKey}` : `${prefixKey}`
    return [children];
  }
}

/**
 * 主要处理key的前缀
 */
function traverseChildren(_children, index = 0, prefixKey, func = c => [c]) {
  if (!Array.isArray(_children)) {
    return null;
  }
  return _children.reduce((result, child, i) => {
    const realIndex = index + i;
    if (Array.isArray(child)) {
      result.push(...traverseChildren(child, realIndex, `${prefixKey}${realIndex}:`, func));
    } else {
      if (child.key) {
        child.key = `${prefixKey}$${child.key}`;
      } else {
        child.key = `${prefixKey}${realIndex}`;
      }
      result.push(...generateChildrenByFunc(child, realIndex, func));
    }
    return result;
  }, []);

}

function mapChildren(children, func, context) {
  //TODO实现此mapChildren方法
  children = traverseChildren(children, 0, '.', func);
  return children;
}

export {
  mapChildren as map,
};